package net.alpenviewer.app;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class MergeTiles {
		
	static final File srcDir    = new File("relief/elevation");
	static final File destDir   = new File("relief/merged_elevation");
	
	public static void merge(int zoomLevel, int tile, int  tileImgName, BufferedImage tileImg) throws IOException {
		File z = new File(destDir.getAbsolutePath() + File.separator + zoomLevel);
		if (!z.exists()) {
			z.mkdir();
		}
		
		File t = new File(destDir.getAbsolutePath() + File.separator + zoomLevel + File.separator + tile);
		if (!t.exists()) {
			t.mkdir();
		}
		
		final File destImgFile = new File(destDir.getAbsolutePath() + File.separator + zoomLevel + File.separator + tile + File.separator + tileImgName + ".png");
		BufferedImage destImg = null;
		if (destImgFile.exists()) {
			destImg = ImageIO.read(destImgFile);
		} else {
			destImg = new BufferedImage(256,256,BufferedImage.TYPE_INT_ARGB);
		} 
		
		for (int y = 0; y < 256; y++) {
			for (int x = 0; x < 256; x++) {
				final int c = tileImg.getRGB(x, y);
				if (c != 0) {
					destImg.setRGB(x, y, c);	
				}				
			}
		}
		
		
		ImageIO.write(destImg, "png", destImgFile);	
		//System.out.println(zoomLevel + " " + tile + " " + tileImgName + " " + destImg);
	}
	
	public static void main(String[] args) throws IOException {
		
		if (!destDir.exists()) {
			destDir.mkdir();
		}

		final File[] mapDirs = srcDir.listFiles();
		for (File mapDir : mapDirs) {			
			if (mapDir.isDirectory()) {					
				final File[] zoomLevelDirs = mapDir.listFiles();
				for (File zoomLevelDir : zoomLevelDirs) {
					if (zoomLevelDir.isDirectory() && zoomLevelDir.getName().matches("^\\d*$")) {						
						final int zoomLevel = Integer.parseInt(zoomLevelDir.getName());						
						final File[] tileDirs = zoomLevelDir.listFiles();
						for (File tileDir : tileDirs) {
							if (tileDir.isDirectory() && tileDir.getName().matches("^\\d*$")) {
								final int tile      = Integer.parseInt(tileDir.getName());
								File[] tileImgs = tileDir.listFiles();
								for (File tileImg : tileImgs) {
									if (tileImg.isFile() && tileImg.getName().toLowerCase().matches("^\\d*\\.png")) {
										String[] n = tileImg.getName().split("\\.");
										if (n.length == 2) {
											final int tileImgName = Integer.parseInt( n[0] );											
											merge(zoomLevel, tile, tileImgName, ImageIO.read(tileImg));
										}																			
									}
								}
							}	
						}				
					}					
				} 			
			}			
		}	
	}
	
}
